import * as React from "react";
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Table, Checkbox, ConfigProvider, InputNumber, message, Modal, Spin } from 'antd';
import { ColumnProps } from 'antd/es/table';
import * as moment from 'moment';
import { ListGUID } from '../../config/ListGuid';
import { CAMLFilter, CAMLCompare, CamlQuery, SPDataType, CamlParam, CamlOrderBy } from './../../config/CAMLHelper';
import './index.scss';
import Api from '../../config/api';
import zhCN from 'antd/es/locale/zh_CN';
import { Link } from "react-router-dom";
import locale from 'antd/es/date-picker/locale/zh_CN';
import { FormComponentProps } from 'antd/lib/form/Form' //获取form表单的interface
import { isHavePermission, isHavePathPermission } from '../../utils/utils'
interface DataType {
  key: React.Key;
  number: string;
  name: string;
  handle: string;
  relative: string;
}
interface fromdata {
  field: string;
  text: string;
  errorMessage: string;
  required: boolean;
  type: string;
  value: any;
  options: any;
  theType: any;
  header: any;
  conditions: any;
}
const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const columns: ColumnProps<DataType>[] = [
  {
    title: '案件编号',
    dataIndex: 'Title',
    key: 'Title',
    align: 'center',
    render(text) {
      let _this = this
      return (
        <div>
          {
            <Link to={{ pathname: 'CaseManagement', state: { id: text, page: 'SearchCaseFile'  } }}>{text}</Link>
          }
        </div>
      )
    },
  },
  {
    title: '受理日',
    dataIndex: 'AcceptTime',
    key: 'AcceptTime',
    align: 'center',
  },
  {
    title: '案件名称',
    dataIndex: 'CaseName',
    key: 'CaseName',
    align: 'center',
  },
  // {
  //   title: '案件内容',
  //   dataIndex: 'handle',
  //   key: 'handle',
  //   align: 'center',
  //   render(text, recod: any) {
  //     return (
  //       <div>
  //         <span>案件概要:{recod.CaseSummary};所属公司:{recod.BelongsCompany};</span>
  //       </div>
  //     )
  //   },
  // }, 
  {
    title: '附件',
    dataIndex: 'file',
    key: 'file',
    align: 'center',
    render: relative => (
      <div>
        {relative && relative.map(tag => {
          const dispUrl = ListGUID.DocumentLink;
          const splitName = tag.Name.split('.');
          return (
            <div key={tag}>
              {
                splitName[splitName.length - 1] === 'xlsx' || splitName[splitName.length - 1] === 'xls' || splitName[splitName.length - 1] === 'docx' || splitName[splitName.length - 1] === 'doc' ? <a href={dispUrl + '?sourcedoc=' + tag.UniqueId} target="_blank">{tag.Name}</a> : <a href={tag.ServerRelativeUrl} download={tag.Name} target="_blank">{tag.Name}</a>
              }

            </div>
          );
        })}
      </div>
    ),
  }
]
const data: DataType[] = [
  {
    key: '1',
    number: 'S s 20200202-01',
    name: '合同1',
    handle: '2022-01-01 ~ 2022-02-02',
    relative: '上海南洋万邦',
  },
  {
    key: '2',
    number: 'B s 20200202-01',
    name: '合同2',
    handle: '2022-01-01 ~ 2022-02-02',
    relative: '上海南洋万邦',
  },
  {
    key: '3',
    number: 'M s 20200202-01',
    name: '合同3',
    handle: '2022-01-01 ~ 2022-02-02',
    relative: '上海南洋万邦',
  },
];
const fromData: fromdata[] = [
  {
    field: 'bianhao',
    text: '案件编号',
    errorMessage: '请选择日期',
    required: false,
    type: 'bianhao',
    value: null,
    options: [],
    theType: 'bianhao',
    header: "LastAnswerTime",
    conditions: "Eq",
  }, {
    field: 'relyOn',
    text: '依赖者名',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: "RelierName",
    conditions: "Contains",
  }, {
    field: 'chuangjian',
    text: '创建日期',
    errorMessage: '请选择日期',
    required: false,
    type: 'chuangjian',
    value: null,
    options: [],
    theType: 'chuangjian',
    header: "Created",
    conditions: "Eq",
  }, {
    field: 'type',
    text: '案件类型',
    errorMessage: '请选择',
    required: false,
    type: 'selects',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "CaseType",
    conditions: "Eq",
  }, {
    field: 'jobid',
    text: '案件受理日',
    errorMessage: '请选择日期',
    required: false,
    type: 'date',
    value: null,
    options: [],
    theType: 'DateTime',
    header: "AcceptTime",
    conditions: "Ge",
  }, {
    field: 'customer',
    text: '法务意见书',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: ['有', '无'],
    theType: 'Text',
    header: "OpinionBook",
    conditions: "Eq",
  }, {
    field: 'date',
    text: '案件最后回答日',
    errorMessage: '请选择日期',
    required: false,
    type: 'date',
    value: null,
    options: [],
    theType: 'DateTime',
    header: "LastAnswerTime",
    conditions: "Ge",
  }, {
    field: 'Lawyerreview',
    text: '律师咨询/参加',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: ['有', '无'],
    theType: 'Text',
    header: "HasLawyer",
    conditions: "Eq",
  }, {
    field: 'mingcheng',
    text: '案件名称',
    errorMessage: '请选择日期',
    required: false,
    type: 'mingcheng',
    value: null,
    options: [],
    theType: 'mingcheng',
    header: "CaseName",
    conditions: "Contains",
  }, {
    field: 'secrecy',
    text: '保密',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: ['是', '否'],
    theType: 'Text',
    header: "NeedSecrecy",
    conditions: "Eq",
  }, {
    field: 'caseSummary',
    text: '案件概要',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: "CaseSummary",
    conditions: "Contains",
  }, {
    field: 'tobear',
    text: '受理担当',
    errorMessage: '请选择',
    required: false,
    type: 'shouli',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "Acceptor",
    conditions: "Contains",
  }, {
    field: 'suoshu',
    text: '所属公司',
    errorMessage: '请输入',
    required: false,
    type: 'selectss',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "BelongsCompany",
    conditions: "Eq",
  }, {
    field: 'other',
    text: '其它',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: "Other",
    conditions: "Contains",
  }


]
const formItemLayout = {
  labelCol: {
    span: 7,

  },
  wrapperCol: {
    offset: 0,
    span: 17,
  },
}

class SearchCaseFile extends React.Component<FormComponentProps>{
  constructor(props: any & FormComponentProps) {
    super(props);
  }
  /**
   * 根据后台返回的 data 中 type 类型生成不同的组件
   * @param item  json
   * @param Component
   */
  switchItem(item) {
    let defaultDateValue = [];
    if(this.state.form.dateOf != "" && this.state.form.dateOf1 != null){
      
      defaultDateValue = [
        moment(this.state.form.dateOf, dateFormat),
        moment(this.state.form.dateOf1, dateFormat),
      ];
    }
    const type = item.type;
    switch (type) {
      case 'Picker':
        return <RangePicker  allowClear format={dateFormat} />;
      case 'int':
        return <InputNumber style={{ width: '100%' }} />;
      case 'char':
        return <Input allowClear style={{ width: '100%' }} placeholder={item.errorMessage} />;
      case 'date':
        return <DatePicker allowClear format={dateFormat} style={{ width: '100%' }} placeholder={item.errorMessage} />;
      case 'select':
        return (
          <Select allowClear style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option} key={option}>{option}</Option>)
              })
            }
          </Select>
        )
      case 'selects':
        return (
          <Select allowClear style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option.Title} key={option.Title}>{option.Title}</Option>)
              })
            }
          </Select>
        )
        case 'selectss':
        return (
          <Select allowClear style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option} key={option}>{option}</Option>)
              })
            }
          </Select>
        )
      case 'multiSelect':
        return (
          <Select allowClear mode='multiple' maxTagCount={3} style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option.username} key={option.ID}>{option.username}</Option>)
              })
            }
          </Select>
        )
      case 'bianhao':
        return (
          <Input.Group compact>
            <Input allowClear style={{ width: '45%', marginRight: 0, textTransform: 'uppercase' }} placeholder="请输入"
              onChange={(event) => { this.change(event, "contract1") }}
              value={this.state.form.contract1} />
            <Input
              className="site-input-split"
              style={{
                width: '10%',
                background: 'white',
                pointerEvents: 'none',
                border: 'none',
              }}
              placeholder="~"
              disabled
              allowClear
            />
            <Input
              className="site-input-right"
              style={{
                width: ' 45%',
              }}
              placeholder="请输入"
              onChange={(event) => { this.change(event, "contract2") }}
              value={this.state.form.contract2}
              allowClear
            />
          </Input.Group>
        )
      case 'chuangjian':
        return (
          <Input.Group compact>
            <RangePicker 
            allowClear
              style={{ width: '100%' }}
              onChange={this.onChangeRangeDate}
              format={"YYYY-MM-DD"}
              defaultValue={defaultDateValue}
              placeholder={['选择开始日期', '选择结束日期']}
            />
          </Input.Group>
        )

      case 'mingcheng':
        return (
          <Input.Group compact>
            <Input
              style={{ width: '100%' }}
              placeholder="请输入"
              onChange={(event) => { this.change(event, "nameCase") }}
              value={this.state.form.nameCase}
              allowClear
            />
          </Input.Group>
        )
      case 'shouli':
        return (
          <Input.Group compact>
            <Select allowClear mode='multiple' placeholder="请选择" style={{ width: '100%' }} value={this.state.form.reviewOnxuan}
              onChange={(event, value) => { this.handleSelectChanges(event, value, "reviewOnxuan") }} maxTagCount={2}>
              {
                this.state.personreviewList.map(element => {
                  return <Option value={element.username} key={element.ID}>{element.username}</Option>
                })
              }
            </Select>
          </Input.Group>
        )
      case 'suoshu':
        return (
          <Input.Group compact>
            <Input
              className="site-input-right"
              style={{
                width: '100%',
              }}
              placeholder="请输入"
              onChange={(event) => { this.change(event, "min") }}
              value={this.state.form.min}
              allowClear
            />
          </Input.Group>
        )
      default:
        return <Input allowClear />;
    }
  }
  state = {
    filter: [],
    pager: {
      current: 1,
      size: 10
    },
    loading: false,
    inSearchOf: false,
    local: zhCN,
    data: [],
    totalnum: 0,
    //表单数据对象
    form: {
      // 案件编号
      theContract: null,
      contract1: null,
      contract2: null,
      //受理日期
      AcceptTime: null,
      dateOf: null,
      dateOf1: null,
      //案件名称
      nameCase: null,
      // 所属公司
      affiliatedCompany: undefined,
      //案件类型
      type: undefined,
      //受理担当
      reviewOnxuan: [],
      reviewOnxuans: null,
      list: [],
      // 审查担当
      personreview: undefined,
      // 我方
      min: null,

    },
    //意见书
    proposalList: ['有', '无'],
    //律师咨询参加
    participateinList: ['有', '无'],
    //保密
    secrecyList: ['是', '否'],
    CasetypeList: [],
    personreviewList: [],
    visible: false,
    weList: []
  }
  onChange = (e, key) => {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e
      }
    })
  }
  getCaption = (obj, state) => {
    var index = obj.lastIndexOf("\-");
    if (state == 0) {
      obj = obj.substring(0, index);
    } else {
      obj = obj.substring(index + 1, obj.length);
    }
    return obj;
  }
  // 输入框改变赋值
  change(e, key) {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e.target.value
      }
    })
  }
  // 下拉框改变赋值
  handleSelectChange(e, key) {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e
      }
    })
  }
  // 下拉框改变赋值
  handleSelectChanges(e, v, key) {
    var arrays = []
    v.forEach(element => {
      arrays.push(`${element.props.value}#${element.props.children}`)
    });
    this.setState({
      form: {
        ...this.state.form,
        reviewOnxuans: arrays.join(';'),
        [key]: e,
        "list": v,
      }
    })
  }
  // 获取日期
  onChangeRangeDate = (value, dateString) => {
    this.setState({
      form: {
        ...this.state.form,
        "dateOf": dateString[0] ? dateString[0] + ' 00:00:00' : '',
        "dateOf1": dateString[1] ? dateString[1] + ' 23:59:59' : ''
      }
    })

  }
  // 高级检索按钮触发
  advancedSearch = () => {
    this.setState({
      visible: true,
    });
  }

  //动态更新绑定数据
  public async componentDidMount() {
    isHavePathPermission()

    let isBack:any;
    isBack = this.props;

    
    // 

    if (isBack.location.state != undefined) {
      let form = JSON.parse(localStorage.getItem('searchForm')); //检索编号
      let formParams = JSON.parse(localStorage.getItem('searchFormParams')); //高级检索
      let PageIndex = JSON.parse(localStorage.getItem('PageIndex')); // 页码
      let pager = this.state.pager;
      pager.current = PageIndex;
      this.setState(pager);

      if(form != null){
        form.AcceptTime = null; //返回时受理日赋不上值但是form里的值不是空的需要清空一下
      }

      
      
      
      
      if(form != null){
        
        this.setState({form},()=>{
          this.retrieve('检索', 1);
        });
      }else if(formParams != null){
        let params = formParams[0].where;
        this.setParamsByCache(params); //高级检索缓存赋值
        this.theQuery(formParams, 1);
      }else{
        this.getData();
      }
      // this.setState({ form })
    }else{
      localStorage.removeItem('searchForm');
      localStorage.removeItem('searchType');
      localStorage.removeItem('searchFormParams');

      fromData.forEach((item, index)=>{
        fromData[index].value = undefined
      })
      
      this.getData();
    }
    
    this.getTest();// 测试代码，调试API使用
    //this.setButtonsEventHandlers();
  }

  setParamsByCache(params:any) {
    let form = this.state.form;

    fromData.forEach((item, index)=>{
      fromData[index].value = undefined
    })

    params.forEach(function(item, index) {
      let key = item.key;
      let type = item.filterType;
      let value = item.value;
      for(let i = 0; i < fromData.length; i++){
        let field = fromData[i].field;

        if(key == '' && type == 'CaseNum'){ //案件编号
          if (value.indexOf('|') > -1) {
            let num = value.split('|');
            form.contract1 = num[0];
            form.contract2 = num[1];
          }else{
            form.contract1 = value;
          }
          
        }else if(key == 'RelierName' && field == 'relyOn'){ //依赖者名
          fromData[i].value = value;
        }else if(key == 'Created' && type == 'Ge'){ //创建时间
          form.dateOf = value;
        }else if(key == 'Created' && type == 'Le'){ //创建时间
          form.dateOf1 = value;
        }else if(key == 'CaseType' && field == 'type'){ //案件类型
          fromData[i].value = value;
        }else if(key == 'AcceptTime' && field == 'jobid'){ //案件受理日
          fromData[i].value = moment(value, "YYYY-MM-DD")
        }else if(key == 'OpinionBook' && field == 'customer'){ //法务意见书
          fromData[i].value = value;
        }else if(key == 'LastAnswerTime' && field == 'date'){ //案件最后回答日
          fromData[i].value = moment(value, "YYYY-MM-DD")
        }else if(key == 'HasLawyer' && field == 'Lawyerreview'){ //律师咨询/参加
          fromData[i].value = value;
        }else if(key == 'CaseName' && field == 'mingcheng'){ //案件名称
          form.nameCase = value;
        }else if(key == 'NeedSecrecy' && field == 'secrecy'){ //保密
          fromData[i].value = value;
        }else if(key == 'CaseSummary' && field == 'caseSummary'){ //案件概要
          fromData[i].value = value;
        }else if(key == 'Acceptor' && field == 'tobear'){ //受理担当
          let valArr = [];
          valArr = value.split(';');
          form.reviewOnxuan = valArr;
        }else if(key == 'BelongsCompany' && field == 'suoshu'){ //所属公司
          fromData[i].value = value;
        }else if(key == 'Other' && field == 'other'){ //其它
          fromData[i].value = value;
        }
      }
    });
    this.setState({form},()=>{
      
      
    });
  }

  // 法务最后回答日
  fwOnChange1 = (date, dateString) => {
    this.setState({
      form: {
        ...this.state.form,
        AcceptTime: dateString
      }
    })
  }
  // 检索合同按钮
  retrieve = (text, isBack = 0) => {

    localStorage.setItem('searchType', text)
    if (this.state.inSearchOf) {
      message.warning('检索中');
      return
    }


    this.setState({
      loading: true,
      inSearchOf: true,
    })
    // 清空选中条件
    // let params: CamlParam[] = [];

    let params: any = [
      {
        logic: "and",
        where: [
          {
            key: 'CaseStatus',
            filterType: "Eq",
            value: "有效"
          }
        ]
      }
    ];

    
    // 判断合同编号1 合同编号2 是否 都有值 
    // 在两输入框全部输入执行 查流水号区间
    if (this.state.form.contract1 != null && this.state.form.contract1 != "" && this.state.form.contract2 != null && this.state.form.contract2 != "") {
      // 在输入框1 2 都有值的情况下 判断输入框1值的格式是否正确
      let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;

      let pattern1 = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)(?![A-Za-z]+$)(?=.*-)(?![0-9]+$)[0-9A-Za-z]*(-)?[0-9]*.*\d$/;

      let number1 = this.state.form.contract1
      let number2 = this.state.form.contract2
      // 
      // if (this.state.form.contract1.indexOf("-") != -1) {
      //   if (pattern1.test(this.state.form.contract1)) {
      //     // 输入整加版本号查询
      //     // 获取完整加版本号的编号 - 前
      //     let numberBefore = this.getCaption(this.state.form.contract1, 0)
      //     // 获取完整加版本号的编号 - 后
      //     let AfterTheNumber = this.getCaption(this.state.form.contract1, 1)

      //     
      //     

      //     // 截取编号最后三位流水号
      //     var str1 = numberBefore.substring(numberBefore.length - 7)
      //     // 我方
      //     var our = numberBefore.slice(0, -9)
      //     // 年份
      //     let year = str1.slice(0, 4)
      //     // 流水号
      //     let serialNumber = str1.substring(str1.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     
      //     serialNumber = parseInt(serialNumber)
      //     // 查询条件
      //     //  我方
      //     // params.push(new CamlParam("BelongsCompany", our, SPDataType.Text, CAMLCompare.Eq));
      //     // 年份
      //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
      //     // 流水号
      //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Geq));//大于等于
          
      //     params[0].where.push({
      //       key: 'BelongsCompany',
      //       filterType: "Eq",
      //       value: our
      //     })
      //     params[0].where.push({
      //       key: 'AcceptYear',
      //       filterType: "Eq",
      //       value: year
      //     })
      //     params[0].where.push({
      //       key: 'SerialNum',
      //       filterType: "Ge",
      //       value: serialNumber
      //     })

      //     //  版本号
      //     //  params.push(new CamlParam("VersionNum", AfterTheNumber, SPDataType.Number, CAMLCompare.Geq));//大于等于

      //   } else {
      //     message.warning('案件编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false
      //     })
      //     return
      //   }
      // } else {
      //   if (pattern.test(this.state.form.contract1)) {
      //     // contract1
      //     // 截取编号最后三位流水号
      //     var str1 = this.state.form.contract1.substring(this.state.form.contract1.length - 7)
      //     // 我方
      //     var our = this.state.form.contract1.slice(0, -9)
      //     // 年份
      //     let year = str1.slice(0, 4)
      //     // 流水号
      //     let serialNumber = str1.substring(str1.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     
      //     serialNumber = parseInt(serialNumber)
      //     // 查询条件
      //     //  我方
      //     // params.push(new CamlParam("BelongsCompany", our, SPDataType.Text, CAMLCompare.Eq));
      //     // 年份
      //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
      //     // 流水号
      //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Geq));//大于等于
      //     params[0].where.push({
      //       key: 'BelongsCompany',
      //       filterType: "Eq",
      //       value: our
      //     })
      //     params[0].where.push({
      //       key: 'AcceptYear',
      //       filterType: "Eq",
      //       value: year
      //     })
      //     params[0].where.push({
      //       key: 'SerialNum',
      //       filterType: "Ge",
      //       value: serialNumber
      //     })
      //   } else {
      //     message.warning('案件编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false
      //     })
      //     return
      //   }

      // }

      // if (this.state.form.contract2.indexOf("-") != -1) {
      //   if (pattern1.test(this.state.form.contract2)) {
      //     // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));


      //     // 输入整加版本号查询
      //     // 获取完整加版本号的编号 - 前
      //     let numberBefore = this.getCaption(this.state.form.contract2, 0)
      //     // 获取完整加版本号的编号 - 后
      //     let AfterTheNumber = this.getCaption(this.state.form.contract2, 1)

      //     
      //     

      //     // 截取编号最后三位流水号
      //     var str1 = numberBefore.substring(numberBefore.length - 7)
      //     // 我方
      //     var our = numberBefore.slice(0, -9)
      //     // 年份
      //     let year = str1.slice(0, 4)
      //     // 流水号
      //     let serialNumber = str1.substring(str1.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     
      //     serialNumber = parseInt(serialNumber)
      //     // 查询条件
      //     //  我方
      //     // params.push(new CamlParam("BelongsCompany", our, SPDataType.Text, CAMLCompare.Eq));
      //     // 年份
      //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
      //     // 流水号
      //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于
      //     //  版本号
      //     //  params.push(new CamlParam("VersionNum", AfterTheNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于

      //     params[0].where.push({
      //       key: 'BelongsCompany',
      //       filterType: "Eq",
      //       value: our
      //     })
      //     params[0].where.push({
      //       key: 'AcceptYear',
      //       filterType: "Eq",
      //       value: year
      //     })
      //     params[0].where.push({
      //       key: 'SerialNum',
      //       filterType: "Le",
      //       value: serialNumber
      //     })

          

      //   } else {
      //     message.warning('案件编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false
      //     })
      //     return
      //   }
      // } else {

      //   // 在输入框1 2 都有值的情况下 判断输入框2值的格式是否正确
      //   if (pattern.test(this.state.form.contract2)) {
      //     // contract2
      //     var str2 = this.state.form.contract2.substring(this.state.form.contract1.length - 7)
      //     let serialNumber2 = str2.substring(str2.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     
      //     serialNumber2 = parseInt(serialNumber2)
      //     // 流水号
      //     // params.push(new CamlParam("SerialNum", serialNumber2, SPDataType.Number, CAMLCompare.Leq));//小于于等于
      //     params[0].where.push({
      //       key: 'SerialNum',
      //       filterType: "Le",
      //       value: serialNumber2
      //     })
      //   } else {
      //     message.warning('案件编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false
      //     })
      //     return
      //   }

      // }

      if (pattern1.test(this.state.form.contract1) && pattern1.test(this.state.form.contract2)) {
        params[0].where.push({
          key: '',
          filterType: "CaseNum",
          value: number1 + "|" + number2
        })
      } else {
          message.warning('案件编号格式有误');
          this.setState({
            loading: false,
            inSearchOf: false
          })
          return
      }
      
    } else if (this.state.form.contract1 != null && this.state.form.contract1 != "") {
      // 如果不满足两个输入框输入条件 判断输入框1是否有值
      let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
      // if (pattern.test(this.state.form.contract1)) {
      //   // params.push(new CamlParam("Title", this.state.form.contract1, SPDataType.Text, CAMLCompare.Contains));
      //   params[0].where.push({
      //     key: 'Title',
      //     filterType: "Contains",
      //     value: this.state.form.contract1
      //   })
      // } else {
      //   message.warning('案件编号格式有误');
      //   this.setState({
      //     loading: false,
      //     inSearchOf: false
      //   })
      //   return
      // }
      if (pattern.test(this.state.form.contract1)) {
        params[0].where.push({
          key: '',
          filterType: "CaseNum",
          value: this.state.form.contract1
        })
      } else {
          message.warning('案件编号格式有误');
          this.setState({
            loading: false,
            inSearchOf: false
          })
         return
      }
      
    } else if (this.state.form.contract2 != null && this.state.form.contract2 != "") {
      // 如果不满足两个输入框输入条件 判断输入框1是否有值
      let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
      // if (pattern.test(this.state.form.contract2)) {
      //   // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
      //   params[0].where.push({
      //     key: 'Title',
      //     filterType: "Contains",
      //     value: this.state.form.contract2
      //   })
      // } else {
      //   message.warning('案件编号格式有误');
      //   this.setState({
      //     loading: false,
      //     inSearchOf: false
      //   })
      //   return
      // }
      if (pattern.test(this.state.form.contract2)) {
        params[0].where.push({
          key: '',
          filterType: "CaseNum",
          value: this.state.form.contract2
        })
      } else {
        message.warning('案件编号格式有误');
        this.setState({
          loading: false,
          inSearchOf: false
        })
        return
      }
      
    }

    // 案件名称
    if (this.state.form.nameCase != null && this.state.form.nameCase != "") {
      // params.push(new CamlParam("CaseName", this.state.form.nameCase, SPDataType.Text, CAMLCompare.Contains));
      params[0].where.push({
        key: 'CaseName',
        filterType: "Contains",
        value: this.state.form.nameCase
      })
    }
    // 案件类型
    if (this.state.form.type != null && this.state.form.type != "") {
      // params.push(new CamlParam("CaseType", this.state.form.type, SPDataType.Text, CAMLCompare.Eq));
      params[0].where.push({
        key: 'CaseType',
        filterType: "Eq",
        value: this.state.form.type
      })
    }
    // 所属公司
    if (this.state.form.affiliatedCompany != null && this.state.form.affiliatedCompany != "") {
      // params.push(new CamlParam("BelongsCompany", this.state.form.affiliatedCompany, SPDataType.Text, CAMLCompare.Eq));
      params[0].where.push({
        key: 'BelongsCompany',
        filterType: "Eq",
        value: this.state.form.affiliatedCompany
      })
    }

    // 开始日期
    if (this.state.form.dateOf != "" && this.state.form.dateOf1 != null) {
      // 2022-10-20T00:00:00Z
      let size = this.state.form.dateOf
      // params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Geq));//我这里用的大于等于，你根据你实际情况来
      params[0].where.push({
        key: 'Created',
        filterType: "Ge",
        value: size
      })
    }

    //结束日期
    if (this.state.form.dateOf1 != "" && this.state.form.dateOf1 != null) {
      let size = this.state.form.dateOf1
      // params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Leq));//我这里用的小于于等于，你根据你实际情况来
      params[0].where.push({
        key: 'Created',
        filterType: "Le",
        value: size
      })
    }

    // 受理单当
    
    
    if ((this.state.form.list != undefined && this.state.form.list != null && this.state.form.list.length != 0) || (this.state.form.reviewOnxuan != undefined && this.state.form.reviewOnxuan != null && this.state.form.reviewOnxuan.length != 0)) {
      // for (let i = 0; i < this.state.form.list.length; i++) {
      //   // params.push(new CamlParam("Acceptor", this.state.form.list[i].key, SPDataType.Text, CAMLCompare.Contains));
      //   params[0].where.push({
      //     key: 'Acceptor',
      //     filterType: "Contains",
      //     value: this.state.form.list[i].props.value.replace("-历史", "")
      //   })

      // }
      params[0].where.push( {
        key: 'Acceptor',
        filterType: "MultiUsers",
        value: this.state.form.reviewOnxuan.map(i => i.replace("-历史","")).join(';')
      })
    }

    // 开始日期
    if (this.state.form.AcceptTime != "" && this.state.form.AcceptTime != null) {
      // 2022-10-20T00:00:00Z
      let size = this.state.form.AcceptTime
      // params.push(new CamlParam("AcceptTime", size, SPDataType.DateTime, CAMLCompare.Eq));//我这里用的大于等于，你根据你实际情况来
      params[0].where.push({
        key: 'AcceptTime',
        filterType: "Ge",
        value: moment(size).format('YYYY-MM-DD')
      })
    }

    let form = this.state.form;
    
    if (form.reviewOnxuan == undefined) {
      localStorage.setItem('searchForm', JSON.stringify(form));
    }else{
      // localStorage.setItem('searchFormList', JSON.stringify(form.list));
      form.list = [];
      localStorage.setItem('searchForm', JSON.stringify(form));
    }

    this.theQuery(params, isBack)
  }
  //弹框取消
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };
  handleSubmit = (e) => {
    this.setState({
      loading: true
    })
    e.preventDefault();
    localStorage.removeItem('searchForm'); //删除普通检索的条件缓存
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // 清空选中条件
        // let params: CamlParam[] = [];
        let params: any = [
          {
            logic: "and",
            where: [
              {
                key: 'CaseStatus',
                filterType: "Eq",
                value: "有效"
              }
            ]
          }
        ];

        for (let i = 0; i < fromData.length; i++) {

          let size = fromData[i].field + ""


          // 是否是 有开始时间结束时间
          let istrue = false
          // 是否是审查担当
          let isReview = false


          if (size == "bianhao") {

            // 在两输入框全部输入执行 查流水号区间
            if (this.state.form.contract1 != null && this.state.form.contract1 != "" && this.state.form.contract2 != null && this.state.form.contract2 != "") {
              // 在输入框1 2 都有值的情况下 判断输入框1值的格式是否正确
              let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;

              let pattern1 = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)(?![A-Za-z]+$)(?=.*-)(?![0-9]+$)[0-9A-Za-z]*(-)?[0-9]*.*\d$/;

              let number1 = this.state.form.contract1
              let number2 = this.state.form.contract2
              // 
              // if (this.state.form.contract1.indexOf("-") != -1) {
              //   if (pattern1.test(this.state.form.contract1)) {
              //     // 输入整加版本号查询
              //     // 获取完整加版本号的编号 - 前
              //     let numberBefore = this.getCaption(this.state.form.contract1, 0)
              //     // 获取完整加版本号的编号 - 后
              //     let AfterTheNumber = this.getCaption(this.state.form.contract1, 1)

              //     
              //     

              //     // 截取编号最后三位流水号
              //     var str1 = numberBefore.substring(numberBefore.length - 7)
              //     // 我方
              //     var our = numberBefore.slice(0, -9)
              //     // 年份
              //     let year = str1.slice(0, 4)
              //     // 流水号
              //     let serialNumber = str1.substring(str1.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     
              //     serialNumber = parseInt(serialNumber)
              //     // 查询条件
              //     //  我方
              //     // params.push(new CamlParam("BelongsCompany", our, SPDataType.Text, CAMLCompare.Eq));
              //     // 年份
              //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
              //     // 流水号
              //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Geq));//大于等于

              //     params[0].where.push({
              //       key: 'BelongsCompany',
              //       filterType: "Eq",
              //       value: our
              //     })
              //     params[0].where.push({
              //       key: 'AcceptYear',
              //       filterType: "Eq",
              //       value: year
              //     })
              //     params[0].where.push({
              //       key: 'SerialNum',
              //       filterType: "Ge",
              //       value: serialNumber
              //     })

              //     //  版本号
              //     //  params.push(new CamlParam("VersionNum", AfterTheNumber, SPDataType.Number, CAMLCompare.Geq));//大于等于

              //   } else {
              //     message.warning('案件编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false
              //     })
              //     return
              //   }
              // } else {
              //   if (pattern.test(this.state.form.contract1)) {
              //     // contract1
              //     // 截取编号最后三位流水号
              //     var str1 = this.state.form.contract1.substring(this.state.form.contract1.length - 7)
              //     // 我方
              //     var our = this.state.form.contract1.slice(0, -9)
              //     // 年份
              //     let year = str1.slice(0, 4)
              //     // 流水号
              //     let serialNumber = str1.substring(str1.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     
              //     serialNumber = parseInt(serialNumber)
              //     // 查询条件
              //     //  我方
              //     // params.push(new CamlParam("BelongsCompany", our, SPDataType.Text, CAMLCompare.Eq));
              //     // 年份
              //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
              //     // 流水号
              //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Geq));//大于等于
              //     params[0].where.push({
              //       key: 'BelongsCompany',
              //       filterType: "Eq",
              //       value: our
              //     })
              //     params[0].where.push({
              //       key: 'AcceptYear',
              //       filterType: "Eq",
              //       value: year
              //     })
              //     params[0].where.push({
              //       key: 'SerialNum',
              //       filterType: "Ge",
              //       value: serialNumber
              //     })
              //   } else {
              //     message.warning('案件编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false
              //     })
              //     return
              //   }

              // }

              // if (this.state.form.contract2.indexOf("-") != -1) {
              //   if (pattern1.test(this.state.form.contract2)) {
              //     // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));


              //     // 输入整加版本号查询
              //     // 获取完整加版本号的编号 - 前
              //     let numberBefore = this.getCaption(this.state.form.contract2, 0)
              //     // 获取完整加版本号的编号 - 后
              //     let AfterTheNumber = this.getCaption(this.state.form.contract2, 1)

              //     
              //     

              //     // 截取编号最后三位流水号
              //     var str1 = numberBefore.substring(numberBefore.length - 7)
              //     // 我方
              //     var our = numberBefore.slice(0, -9)
              //     // 年份
              //     let year = str1.slice(0, 4)
              //     // 流水号
              //     let serialNumber = str1.substring(str1.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     
              //     serialNumber = parseInt(serialNumber)
              //     // 查询条件
              //     //  我方
              //     // params.push(new CamlParam("BelongsCompany", our, SPDataType.Text, CAMLCompare.Eq));
              //     // 年份
              //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
              //     // 流水号
              //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于
              //     //  版本号
              //     //  params.push(new CamlParam("VersionNum", AfterTheNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于

              //     params[0].where.push({
              //       key: 'BelongsCompany',
              //       filterType: "Eq",
              //       value: our
              //     })
              //     params[0].where.push({
              //       key: 'AcceptYear',
              //       filterType: "Eq",
              //       value: year
              //     })
              //     params[0].where.push({
              //       key: 'SerialNum',
              //       filterType: "Le",
              //       value: serialNumber
              //     })



              //   } else {
              //     message.warning('案件编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false
              //     })
              //     return
              //   }
              // } else {

              //   // 在输入框1 2 都有值的情况下 判断输入框2值的格式是否正确
              //   if (pattern.test(this.state.form.contract2)) {
              //     // contract2
              //     var str2 = this.state.form.contract2.substring(this.state.form.contract1.length - 7)
              //     let serialNumber2 = str2.substring(str2.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     
              //     serialNumber2 = parseInt(serialNumber2)
              //     // 流水号
              //     // params.push(new CamlParam("SerialNum", serialNumber2, SPDataType.Number, CAMLCompare.Leq));//小于于等于
              //     params[0].where.push({
              //       key: 'SerialNum',
              //       filterType: "Le",
              //       value: serialNumber2
              //     })

              //   } else {
              //     message.warning('案件编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false
              //     })
              //     return
              //   }

              // }
              if (pattern1.test(this.state.form.contract1) && pattern1.test(this.state.form.contract2)) {
                params[0].where.push({
                  key: '',
                  filterType: "CaseNum",
                  value: number1 + "|" + number2
                })
              } else {
                    message.warning('案件编号格式有误');
                    this.setState({
                      loading: false,
                      inSearchOf: false
                    })
                    return
              }
              
            } else if (this.state.form.contract1 != null && this.state.form.contract1 != "") {
              // 如果不满足两个输入框输入条件 判断输入框1是否有值
              let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
              // if (pattern.test(this.state.form.contract1)) {
              //   // params.push(new CamlParam("Title", this.state.form.contract1, SPDataType.Text, CAMLCompare.Contains));
              //   params[0].where.push({
              //     key: 'Title',
              //     filterType: "Contains",
              //     value: this.state.form.contract1
              //   })
              // } else {
              //   message.warning('案件编号格式有误');
              //   this.setState({
              //     loading: false,
              //     inSearchOf: false
              //   })
              //   return
              // }
              if (pattern.test(this.state.form.contract1)) {
                params[0].where.push({
                  key: '',
                  filterType: "CaseNum",
                  value: this.state.form.contract1
                })
              } else {
                  message.warning('案件编号格式有误');
                  this.setState({
                    loading: false,
                    inSearchOf: false
                  })
                  return
              }
              
            } else if (this.state.form.contract2 != null && this.state.form.contract2 != "") {
              // 如果不满足两个输入框输入条件 判断输入框1是否有值
              let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
              // if (pattern.test(this.state.form.contract2)) {
              //   // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
              //   params[0].where.push({
              //     key: 'Title',
              //     filterType: "Contains",
              //     value: this.state.form.contract2
              //   })
              // } else {
              //   message.warning('案件编号格式有误');
              //   this.setState({
              //     loading: false,
              //     inSearchOf: false
              //   })
              //   return
              // }
              if (pattern.test(this.state.form.contract2)) {
                params[0].where.push({
                  key: '',
                  filterType: "CaseNum",
                  value: this.state.form.contract2
                })
              } else {
                  message.warning('案件编号格式有误');
                  this.setState({
                    loading: false,
                    inSearchOf: false
                  })
                  return
              }
              
            }


          } else if (size == "mingcheng") {
            // 合同名称
            if (this.state.form.nameCase != null && this.state.form.nameCase != "") {
              // this.fuzzy("ContractName", this.state.form.nameCase, "Text", "", "")
              // params.push(new CamlParam("CaseName", this.state.form.nameCase, SPDataType.Text, CAMLCompare.Contains));
              params[0].where.push({
                key: 'CaseName',
                filterType: "Contains",
                value: this.state.form.nameCase
              })
            }
          } else if (size == "tobear") {
            // 法务受理担当
            
            
            
            if ((this.state.form.list != undefined && this.state.form.list != null && this.state.form.list.length != 0) || (this.state.form.reviewOnxuan != undefined && this.state.form.reviewOnxuan != null && this.state.form.reviewOnxuan.length != 0)) {
              // for (let i = 0; i < this.state.form.list.length; i++) {
              //   // params.push(new CamlParam("Acceptor", this.state.form.list[i].key, SPDataType.Text, CAMLCompare.Contains));
              //   params[0].where.push({
              //     key: 'Acceptor',
              //     filterType: "Contains",
              //     value: this.state.form.list[i].props.value.replace("-历史", "")
              //   })

              // }
              params[0].where.push( {
                key: 'Acceptor',
                filterType: "MultiUsers",
                value: this.state.form.reviewOnxuan.map(i => i.replace("-历史","")).join(';')
              })
            }
          }
          // else if (size == "suoshu") {
          //   // 所属公司
          //   if (this.state.form.affiliatedCompany != null && this.state.form.affiliatedCompany != "") {
          //     // this.fuzzy("Our", this.state.form.min, "Text", "", "")
          //     // params.push(new CamlParam("BelongsCompany", this.state.form.min, SPDataType.Text, CAMLCompare.Contains));
          //     params[0].where.push({
          //       key: 'BelongsCompany',
          //       filterType: "Eq",
          //       value: this.state.form.affiliatedCompany
          //     })
          //   }
          // }
          else if (size == "chuangjian") {
            // 开始日期
            if (this.state.form.dateOf != "" && this.state.form.dateOf1 != null) {
              // 2022-10-20T00:00:00Z
              let size = this.state.form.dateOf
              let size1 = this.state.form.dateOf1
              // params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Geq));//我这里用的大于等于，你根据你实际情况来

              params[0].where.push({
                key: 'Created',
                filterType: "Ge",
                value: size
              })
              params[0].where.push({
                key: 'Created',
                filterType: "Le",
                value: size1
              })
            }

            //结束日期
            // if (this.state.form.dateOf1 != "" && this.state.form.dateOf1 != null) {
            //   let size = this.state.form.dateOf1
            //   params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Leq));//我这里用的小于于等于，你根据你实际情况来
            // }
          } else {
            if (size == "date" && values.date != null && values.date != undefined && values.date != "") {
              values.date = moment(values.date).format('YYYY-MM-DD')
              values.date = values.date
            }
            if (size == "jobid" && values.jobid != null && values.jobid != undefined && values.jobid != "") {
              values.jobid = moment(values.jobid).format('YYYY-MM-DD')
              values.jobid = values.jobid
            }
            // 审查担当
            if (size == "tobear" && values.tobear != null && values.tobear != undefined && values.tobear != "") {
              isReview = true
            }
            if (values[`${size}`] != null && values[`${size}`] != undefined && values[`${size}`] != "") {
              if (!istrue) {
                // 判断是否是多选框 审查担当
                if (isReview) {
                  for (let i = 0; i < values.tobear.length; i++) {
                    // params.push(new CamlParam("Acceptor", values.tobear[i], SPDataType.Text, CAMLCompare.Contains));
                    // params[0].where.push({
                    //   key: 'Acceptor',
                    //   filterType: "Contains",
                    //   value: values.tobear[i].replace("-历史", "")
                    // })
                    values.tobear[i].replace("-历史", "")
                  }
                  params[0].where.push( {
                    key: 'Acceptor',
                    filterType: "MultiUsers",
                    value: values.tobear.join(';')
                  })
                  isReview = false
                } else {
                  // params.push(new CamlParam(fromData[i].header, values[`${size}`], SPDataType[`${fromData[i].theType}`], CAMLCompare[`${fromData[i].conditions}`]));
                  params[0].where.push({
                    key: fromData[i].header,
                    filterType: fromData[i].conditions,
                    value: values[`${size}`]
                  })
                }
              } else {
                // params.push(new CamlParam(fromData[i].header, values.Legalacceptancedate[0], SPDataType.DateTime, CAMLCompare.Geq));
                // params.push(new CamlParam(fromData[i].header, values.Legalacceptancedate[1], SPDataType.DateTime, CAMLCompare.Leq));

                params[0].where.push({
                  key: fromData[i].header,//属性名称
                  filterType: "Ge",//检索方式
                  value: values.Legalacceptancedate[0]//检索的值
                })
                params[0].where.push({
                  key: fromData[i].header,
                  filterType: "Le",
                  value: values.Legalacceptancedate[1]
                })


                istrue = false
              }

            }

          }

        }

        // 检索
        
        localStorage.setItem('searchFormParams', JSON.stringify(params)); //缓存高级检索item
        this.theQuery(params)

        this.setParamsByCache(params[0].where); //赋值高级检索弹框params
        // 关闭弹窗
        this.setState({
          visible: false,
          confirmLoading: false,
        });

      }
    });
  }
  public render(): React.ReactElement {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className='box'>
        <Spin  spinning={this.state.loading}>
        <div className="box_content">
          <div className="box_top">

            <Row type="flex" justify="end">
                {
                  isHavePermission('SearchCaseFile/moresearch') ? <Col><Button type="primary" className="Button_1" onClick={this.advancedSearch} >高级检索</Button></Col> : null
                }
                {
                  isHavePermission('SearchCaseFile/search') ? <Col><Button type="primary" onClick={this.retrieve}>检索</Button></Col> : null
                }

            </Row>

            <div className="placeholder"></div>

            <Row type="flex" align="middle" justify="space-between">

              <Col span={7}>
                <Form.Item label='案件编号' labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <Row type="flex" justify="space-between" align="middle">
                    <Col span={11}>
                      <Input allowClear value={this.state.form.contract1} placeholder="请输入"
                        onChange={(event) => { this.change(event, "contract1") }} width='100%' style={{ textTransform: 'uppercase' }} />
                    </Col>
                    <Col span={2}>
                      <div className="size">~</div>
                    </Col>
                    <Col span={11}>
                      <Input allowClear value={this.state.form.contract2} placeholder="请输入"
                        onChange={(event) => { this.change(event, "contract2") }} width='100%' />
                    </Col>
                  </Row>
                </Form.Item>

              </Col>
              <Col span={7}>

                <Form.Item label="案件受理日" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  {/* {
                    getFieldDecorator('data1', {
                    })(<RangePicker allowClear 
                      onChange={this.onChangeRangeDate}
                      locale={locale}
                      style={{ width: '100%' }}
                      format={"YYYY-MM-DD"}
                      placeholder={['选择开始日期', '选择结束日期']}
                    />)
                  } */}
                  <DatePicker allowClear style={{ width: '100%' }} placeholder="请选择年份" onChange={this.fwOnChange1} format={"YYYY-MM-DD"} />
                </Form.Item>

              </Col>
              <Col span={7}>

                <Form.Item label="案件名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <Input allowClear value={this.state.form.nameCase} placeholder="请输入"
                    onChange={(event) => { this.change(event, "nameCase") }} style={{
                      width: '100%',
                    }} />
                </Form.Item>

              </Col>
              <Col span={7}>

                <Form.Item label="所属公司" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <Select allowClear
                    style={{
                      width: '100%',
                    }}
                    onChange={(event) => { this.handleSelectChange(event, "affiliatedCompany") }}
                    placeholder="请选择"
                    value={this.state.form.affiliatedCompany}
                  >
                    {
                      this.state.weList.map(element => {
                        return <Option value={element} key={element}>{element}</Option>
                      })
                    }
                  </Select>
                  {/* <Input  allowClear value={this.state.form.affiliatedCompany}
                    onChange={(event) => { this.change(event, "affiliatedCompany") }} placeholder="请输入" style={{
                      width: '100%',
                    }} /> */}
                </Form.Item>

              </Col>
              <Col span={7} >
                <Form.Item label='案件类型' labelAlign="left" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>

                  <Select
                    allowClear
                    placeholder="请选择内容"
                    value={this.state.form.type}
                    style={{
                      width: '100%',
                    }}
                    onChange={(event) => { this.handleSelectChange(event, "type") }}
                  >
                    {
                      this.state.CasetypeList.map(element => {
                        return <Option value={element.Title} key={element.ID}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>
              <Col span={7} >
                <Form.Item label='受理担当' labelAlign="left" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                  <Select allowClear mode='multiple' placeholder="请选择" style={{ width: '100%' }} value={this.state.form.reviewOnxuan}
                    onChange={(event, value) => { this.handleSelectChanges(event, value, "reviewOnxuan") }} maxTagCount={1}>
                    {
                      this.state.personreviewList.map(element => {
                        return <Option value={element.username} key={element.ID}>{element.username}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>
            </Row>
          </div>
          {/* <div className="placeholder"></div> */}
          <div style={{ height: '24px' }}></div>
          <div className="box_toble">
            <ConfigProvider locale={this.state.local}>
              <Table columns={columns} dataSource={this.state.data}
                pagination={{
                  onChange: (page, pageSize?) => {
                    this.setState({
                      pager: {
                        current: page,
                        size: pageSize
                      }
                    }, () => {
                      this.getData()
                    })

                  },
                  onShowSizeChange: (page, pageSize?) => {
                    this.setState({
                      pager: {
                        current: page,
                        size: pageSize
                      }
                    }, () => this.getData())
                  },
                  current: this.state.pager.current,
                  pageSize: this.state.pager.size,
                  hideOnSinglePage: false,
                  total: this.state.totalnum,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  defaultCurrent: 1,
                  showTotal: function (total) {
                    return `总共有 ${total} 条数据`;
                  }
                }} />
            </ConfigProvider>
          </div>
          <Modal
            destroyOnClose={true}
            visible={this.state.visible}
            onCancel={this.handleCancel}
            closable={false}
            footer={null}
            width={'63%'}
          >
            <Form onSubmit={this.handleSubmit} layout='inline' >
              <Row>
                {
                  fromData.map((item, index) => {
                    // type 为 date 日期格式需要强制转化为 moment 格式
                    item.value = item.type == 'date' ? item.value == null ? null : moment(item.value, 'YYYY-MM-DD') : item.value;
                    // item.value = item.type == 'date' ? moment(item.value, 'YYYY-MM-DD') : item.value;
                    return (
                      <Col span={11} offset={index % 2 == 0 ? 0 : 2}>
                        <Form.Item
                          key={index}
                          {...formItemLayout}
                          label={item.text}
                          style={{ display: 'flex', marginTop: '15px' }}
                        >
                          {getFieldDecorator(item.field, {
                            initialValue: item.value,
                            rules: [{
                              required: item.required,
                              message: item.errorMessage
                            }],
                          })(
                            this.switchItem(item)
                          )}
                        </Form.Item>
                      </Col>

                    )
                  })
                }
              </Row>
              <div style={{ height: '24px' }}></div>
              <Row>
                <Col span={3} offset={9}>
                  <Form.Item>
                    <Button type="primary" style={{ padding: ' 0 24px' }} onClick={this.handleSubmit}>检索</Button>
                  </Form.Item>
                </Col>
                <Col span={3}>
                  <Form.Item>
                    <Button type="default" style={{ padding: ' 0 24px' }} onClick={this.handleCancel}>取消</Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
        </div>
        </Spin>
        
      </div>

    );
  }
  async getData() {
    this.setState({
      loading: true
    })

    let filter = this.state.filter;
    if (filter.length == 0) { // 如果是刚进来的页面，默认检索有效的数据
      filter = [
        {
          logic: "and",
          where: [
            {
              key: 'CaseStatus',
              filterType: "Eq",
              value: "有效"
            }
          ]
        }
      ];
    }

    
    

    localStorage.setItem('PageIndex', JSON.stringify(this.state.pager.current)); //设置页码
    let Naturcontract = await Api._getPaged({ Guid: ListGUID.CaseManagement, PageSize: this.state.pager.size, PageIndex: this.state.pager.current, FilterL: filter });
    if(Naturcontract.data) {
      for (let i = 0; i < Naturcontract.data.length; i++) {
        if (Naturcontract.data[i].FileAddress != null) {
          // 
          let file = await Api.getFiles(`${ListGUID.CaseLibRelativeUrl}/${Naturcontract.data[i].FileAddress}`);
          // 处理时间排序
          file.sort(function (a, b) {
            return b.TimeCreated < a.TimeCreated ? -1 : 1
          })
          Naturcontract.data[i].file = file
        } else {
          Naturcontract.data[i].file = []
        }
        Naturcontract.data[i].AcceptTime = Naturcontract.data[i].AcceptTime ? moment(Naturcontract.data[i].AcceptTime).format('YYYY-MM-DD') : ''

      }
  
      this.setState({
        data: Naturcontract.data,
        totalnum: Naturcontract.Total,
        loading: false,
        inSearchOf: false,
  
      })
    } else {
      this.setState({
        loading: false,
        inSearchOf: false,
      })
    }
    
  }
  public async getTest() {


    var param4 = {
      Guid: ListGUID.Companies // 公司设置
    };
    // let Companysettings = await Api._getModel(param4);
    let Companysettings = JSON.parse(sessionStorage.getItem('userDataPer')).PermissionCompany

    fromData[12].options = Companysettings

    // Naturcontract.forEach(async element => {

    let Persons = await Api._getModel({ Guid: ListGUID.CaseType });


    fromData[3].options = Persons

    let Person = await Api._getModel({ Guid: ListGUID.ReviewOn });
    const userList = JSON.parse(localStorage.getItem('usersList'));
    Person.forEach(async item => {
      item.username = item.Title
      // let informationid = await Api.GetUserById(item.ReviewUserId)
      let informationid = userList.filter(i => i.id === item.ReviewUserId)
      if (informationid && informationid.length > 0) {
        item.Title = informationid.Title
      }

      // return
    });
    let historyReviewOn = Person.filter(i => i.Title.includes('-历史'));
    let nowReviewOn = Person.filter(i => !i.Title.includes('-历史'))
    Person = [...nowReviewOn, ...historyReviewOn];
    fromData[13].options = Person
    setTimeout(() => {
      this.setState({
        personreviewList: Person,
        CasetypeList: Persons,
        weList: Companysettings
      })
    }, 300)

  }
  public async theQuery(params, isBack = 0) {
    if (isBack == 0) {
      this.setState({
        filter: params || [],
        // 检索的时候 是新list 需要把页码重置
        pager: {
          current: 1,
          size: 10
        }
      }, () => {
        this.getData()
      })
    }else{
      this.setState({
        filter: params || [],
        //从详情页返回不重置页码 
      }, () => {
        this.getData()
      })
    }
    // var param2 = {
    //   Guid: ListGUID.CaseManagement, //表数据
    //   PageSize: this.state.pager.size,
    //   PageIndex: this.state.pager.current
    // };


    // let Naturcontract = await Api._getPaged(param2);

    // // Naturcontract.forEach(async element => {


    // let size = 0
    // // 追加附件的数据数量
    // let num = 10

    // if (Naturcontract.data.length < 10) {
    //   num = Naturcontract.length
    // }

    // let arr = []
    // for (let i = 0; i < num; i++) {
    //   
    //   arr.push(Naturcontract.data[size])
    //   size++
    // }

    // arr.forEach(async element => {
    //   if (element.FileAddress != null) {
    //     let file = await Api.getFiles(`${ListGUID.CommonLibRelativeUrl} + '/' + ${element.FileAddress}`);
    //     element.file = file
    //   } else {
    //     element.file = []
    //   }
    // });




    // setTimeout(() => {
    //   
    //   this.setState({
    //     data: Naturcontract.data,
    //     totalnum: Naturcontract.Total,
    //     loading: false,
    //     inSearchOf: false,
    //   })
    // }, 1000)


    return
    let camlQuery = {
      ViewXml: ''
    }
    //不排序
    let demo = Api.buildCamlXml(params);

    camlQuery.ViewXml = demo
    

    let Naturcontract1 = await Api.GetListItemsByCAMLQuery(ListGUID.CaseManagement, camlQuery);

    // Naturcontract1 = await Api._getPermissionData(ListGUID.CaseManagement, Naturcontract1)

    Naturcontract1.forEach(async element => {

      if (element.FileAddress != null) {
        let file = await Api.getFiles(`${ListGUID.CommonLibRelativeUrl} + '/' + ${element.FileAddress}`);
        // 处理时间排序
        file.sort(function (a, b) {
          return b.TimeCreated < a.TimeCreated ? -1 : 1
        })
        element.file = file
      } else {
        element.file = []
      }
    });

    setTimeout(() => {
      this.setState({
        data: Naturcontract1,
        totalnum: Naturcontract1.length,
        loading: false,
        inSearchOf: false
      })
    }, 1000)
  }

  // 切换分页
  public async ontab(e) {

    let size = e * 10 - 10
    
    // 追加附件的数据数量
    let num = 10
    let arr = []
    for (let i = 0; i < num; i++) {
      
      arr.push(this.state.data[size])
      size++
    }

    arr.forEach(async element => {
      if (element.FileAddress != null) {
        let file = await Api.getFiles(`${ListGUID.CommonLibRelativeUrl} + '/' + ${element.FileAddress}`);
        // 处理时间排序
        file.sort(function (a, b) {
          return b.TimeCreated < a.TimeCreated ? -1 : 1
        })
        element.file = file
      } else {
        element.file = []
      }
    });

    
    


  }


}
export default Form.create()(SearchCaseFile);